import React, { useEffect, useState } from "react";
import { getPsInfo, getUser, modifyUserPermission } from "../../api";
import { Button, Table } from "antd";
import { ColumnsType } from "antd/es/table";
import { Tag, Modal, Checkbox, message as antdMessage } from "antd";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
import { useTranslation } from "react-i18next";
interface UserState {
  id: number | string;
  ps_ids: string;
  role_name: string;
  user: string;
  user_name: string;
  role_id: string;
  permission_list: {
    ps_id: string | number;
    ps_name: string;
  }[];
}

interface PsInfoState {
  value: string | number;
  label: string;
}

const Admin: React.FC = () => {
  const [users, setUsers] = useState<UserState[]>([]);
  const qweqw = 1;
  const { t } = useTranslation()
  const columns: ColumnsType<UserState> = [
    {
      key: "id",
      title: "ID",
      dataIndex: "id",
    },
    {
      key: "role_name",
      title: t('administrator.roleName'),
      dataIndex: "role_name",
    },
    {
      key: "user",
      title: t('administrator.user'),
      dataIndex: "user",
    },
    {
      key: "user_name",
      title: t('administrator.username'),
      dataIndex: "user_name",
    },
    {
      key: "ps_ids",
      title: t('administrator.ps_ids'),
      dataIndex: "ps_ids",
    },
    {
      key: "permission_list",
      title: t('administrator.permission_list'),
      dataIndex: "permission_list",
      render(_) {
        return (
          <div>
            {_.map((v) => {
              return <Tag key={v.ps_id}>{v.ps_name}</Tag>;
            })}
          </div>
        );
      },
    },
    {
      key: "opration",
      title: t('administrator.opration'),
      render(_) {
        return (
          <div>
            <Button type="primary" onClick={() => showModal(_)}>
              { t('administrator.modify') }
            </Button>
          </div>
        );
      },
    },
  ];
  const [psInfo, setPsInfo] = useState<PsInfoState[]>([]);
  const [selectPsIds, setSelectPsIds] = useState<string[]>([]);
  const [roleID, setRoleID] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = (_: UserState) => {
    setIsModalOpen(true);
    setSelectPsIds(_.ps_ids.split(","));
    setRoleID(_.role_id);
  };

  const handleOk = async () => {
    const resp = await modifyUserPermission({
      role_id: roleID,
      ps_ids: selectPsIds.join(","),
    });
    const { code, message } = resp.data;
    if (code === 200) {
      antdMessage.success(message);
      fetchUsers();
    } else {
      antdMessage.error(message);
    }
    setIsModalOpen(false);
  };

  const fetchUsers = async () => {
    const resp = await getUser();
    setUsers(resp.data);
  };
  // console.log("🚀 ~ file: index.tsx ~ line 112 ~ fetchUsers ~ fetchUsers", fetchUsers)
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onChange = (checkedValues: CheckboxValueType[]) => {
    setSelectPsIds(checkedValues as string[]);
  };

  useEffect(() => {
    fetchUsers();

    (async () => {
      const resp = await getPsInfo();
      const s = resp.data.map((v) => ({
        label: v.ps_name,
        value: v.ps_id.toString(),
      }));
      setPsInfo(s);
    })();
  }, []);

  return (
    <div>
      <Table<UserState>
        columns={columns}
        dataSource={users}
        rowKey={(record) => record.id}
      />
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Checkbox.Group
          options={psInfo}
          value={selectPsIds}
          onChange={onChange}
        />
      </Modal>
    </div>
  );
};

export default Admin;
